package _interview100;

/**
 * 62. 不同路径
 */
public class No62 {
    private int[][] cache;

    public int uniquePaths1(int m, int n) {
        cache = new int[m + 1][n + 1];
        return dfs(m, n);
    }

    private int dfs(int i, int j) {
        if (i < 1 || j < 1) return 0;
        else if (cache[i][j] != 0) return cache[i][j];
        else if (i == 1 && j == 1) return cache[i][j] = 1;
        else return cache[i][j] = dfs(i - 1, j) + dfs(i, j - 1);
    }

    public int uniquePaths2(int m, int n) {
        int[][] f = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1 && j == 1) f[i][j] = 1;
                else f[i][j] = f[i - 1][j] + f[i][j - 1];
            }
        }
        return f[m][n];
    }

    public int uniquePaths4(int m, int n) {
        int[] f = new int[n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1 && j == 1) f[j] = 1;
                else f[j] = f[j] + f[j - 1];
            }
        }
        return f[n];
    }
}
